package com.china08.yxyapi.util;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 播放地址生成器:微课
 * 
 * @author Ertao.Fang
 *
 */
@Component
public class YxyPlayUrlForWeiKechengBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyPlayUrlForWeiKechengBuilder.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${salt.weikecheng}")
    private String salt = "";

    @Value("${yxy.res.url}")
    private String yxy_res_url;

    public String resourceId = "";
    public String userId = "";
    public Boolean resVip = false;
    public Boolean userVip = false;
    public String viewFrom = "";
    public Integer freeTimes = 0;

    public String build() {
        String url = "";
        try {
            url = build_internal();
        } catch (Exception e) {
            LOGGER.error("生成播放地址失败:" + e.getMessage());
        }
        return url;
    }

    private String build_internal() throws Exception {
        // ##
        // 时间戳
        Long ts = System.currentTimeMillis();

        // ##
        // Salt
        String secretKey = DigestUtils.md5Hex(salt + ":" + resourceId + ":" + ts);

        // ##
        // TokeMap
        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("ts", ts);
        tokenMap.put("userId", userId);
        tokenMap.put("resVip", resVip); // 资源VIP
        tokenMap.put("userVip", userVip);// 个人VIP
        tokenMap.put("viewFrom", viewFrom);// 浏览入口
        tokenMap.put("freeTimes", freeTimes);// 免费观看次数
        tokenMap.put("resourceId", resourceId);// 资源ID

        // ##
        // TokenJsonStr
        String tokenJson = objectMapper.writeValueAsString(tokenMap);
        // ##
        // TokenEncrypted
        String tokenEncrypted = DESUtil.encryption(tokenJson, secretKey);
        // ##
        // TokenBase64
        String tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncrypted.getBytes());
        tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncryptedBase64.getBytes());
        tokenEncryptedBase64 = Base64.getEncoder().encodeToString(tokenEncryptedBase64.getBytes());
        // ##
        // TokenBase64UrlEncoded
        String tokenEncryptedBase64UrlEncoded = URLEncoder.encode(tokenEncryptedBase64, "UTF-8");
        // ##
        // sign
        String sign = DigestUtils.md5Hex(tokenJson + ":" + secretKey);
        // ##
        // query string
        String queryParamStr = "" //
                + "token=" + tokenEncryptedBase64UrlEncoded + "&" //
                + "sign=" + sign + "&"//
                + "ts=" + ts;
        LOGGER.info("ts:" + ts);
        LOGGER.info("sign:" + sign);
        LOGGER.info("tokenJson:" + tokenJson);
        LOGGER.info("tokenEncrypted:" + tokenEncrypted);
        LOGGER.info("tokenEncryptedBase64:" + tokenEncryptedBase64);
        LOGGER.info("tokenEncryptedBase64UrlEncoded:" + tokenEncryptedBase64UrlEncoded);
        LOGGER.info("secretKey:" + secretKey);
        // ##
        // full url
        String fullUrl = ""//
                + yxy_res_url + "/res/browseWeiKecheng/" + resourceId// 播放路径
                + "?" + queryParamStr; // 授权签名
        return fullUrl;
    }

    public YxyPlayUrlForWeiKechengBuilder setResourceId(String resourceId) {
        this.resourceId = resourceId;
        return this;
    }

    public YxyPlayUrlForWeiKechengBuilder setUserId(String userId) {
        this.userId = userId;
        return this;
    }

    public YxyPlayUrlForWeiKechengBuilder setViewFrom(String viewFrom) {
        this.viewFrom = viewFrom;
        return this;
    }

    public YxyPlayUrlForWeiKechengBuilder setResVip(Boolean resVip) {
        this.resVip = resVip;
        return this;
    }

    public YxyPlayUrlForWeiKechengBuilder setUserVip(Boolean userVip) {
        this.userVip = userVip;
        return this;
    }

    public YxyPlayUrlForWeiKechengBuilder setFreeTimes(Integer freeTimes) {
        this.freeTimes = freeTimes;
        return this;
    }

    // @Autowired
    // YxyPlayUrlForWeiKechengBuilder builder;
    //
    // public static void main(String[] args) {
    // YxyPlayUrlForWeiKechengBuilder builder = new
    // YxyPlayUrlForWeiKechengBuilder();
    // String url = builder//
    // .setResourceId("2c908a1c5a697682015a6998ead00000")// 资源ID:必填
    // .setUserId("1234567890")// 用户ID:必填
    // .setUserVip(true)// 个人VIP:选填:默认false
    // .setResVip(true)// 资源VIP:选填:默认:false
    // .setFreeTimes(10)// 免费播放次数:选填:默认:0
    // .setViewFrom("weikecheng")//
    // // 浏览来源:必填:weikecheng/mistakes错题本填"mistakes",直接首页浏览微课填"weikecheng"
    // .build();
    // System.out.println(url);
    // }
}
